package io.yuanqi.hgtcshop.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class CountdownTimer {
    private static Map<String, Long> countdownTimers = new ConcurrentHashMap<>();

//    public void startCountdown(String userId, long duration) {
//        long startTime = System.currentTimeMillis();
//        long endTime = startTime + TimeUnit.MINUTES.toMillis(duration);
//        countdownTimers.put(userId, endTime);
//    }

    public void startCountdown(String userId) {
        long startTime = System.currentTimeMillis();
        long endTime = startTime + TimeUnit.SECONDS.toMillis(900); // 900 秒为 15 分钟
        countdownTimers.put(userId, endTime);
    }

    public Long getTime(String key){
        return countdownTimers.get(key);
    }

    public Long putTime(String key,Long value){
        return countdownTimers.put(key,value);
    }

//    public long[] getCurrentCountdownTime(String userId) {
//        long endTime = countdownTimers.getOrDefault(userId, 0L);
//        long currentTime = System.currentTimeMillis();
//        long remainingTime = Math.max(0, endTime - currentTime);
//        long remainingMinutes = TimeUnit.MILLISECONDS.toMinutes(remainingTime);
//        long remainingSeconds = TimeUnit.MILLISECONDS.toSeconds(remainingTime)
//                - TimeUnit.MINUTES.toSeconds(remainingMinutes);
//        return new long[] { remainingMinutes, remainingSeconds };
//    }

    public long getCurrentCountdownTime(String userId) {
        long endTime = countdownTimers.getOrDefault(userId, 0L);
        long currentTime = System.currentTimeMillis();
        long remainingTime = Math.max(0, endTime - currentTime);
        return TimeUnit.MILLISECONDS.toSeconds(remainingTime);
    }

    public void cancelCountdown(String userId) {
        countdownTimers.remove(userId);
    }

//    public static TimeVO getTimer(String userId) {
//        CountdownTimer timer = new CountdownTimer();
//        // 模拟开始倒计时
//        timer.startCountdown(userId, 15);
//
//        // 模拟倒计时进行中，每隔一段时间查询一次倒计时时间
//        for (int i = 0; i < 16 * 60; i++) {
//            try {
//                Thread.sleep(1000); // 模拟1秒钟的时间流逝
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            long[] currentCountdownTime = timer.getCurrentCountdownTime(userId);
//            System.out.println("剩余倒计时时间：" + currentCountdownTime[0] + " 分钟 " + currentCountdownTime[1] + " 秒");
//
//            if (currentCountdownTime[0] <= 0 && currentCountdownTime[1] <= 0) {
//                System.out.println("倒计时结束，取消倒计时");
//                timer.cancelCountdown(userId);
//                break;
//            }
//        }
//        return null;
//    }


}